<?php


namespace app\common\model;


use think\facade\Db;
use think\Model;

class Bill extends Model
{


    /**
     * 获取指定日期报表
     * @param $user
     * @param $year
     * @param $month
     * @param $week
     */
    public static function getReportTable($user, $year, $month, $week, $type)
    {

        $year_data = [];
        $month_data = [];
        $week_data = [];
        if ($month) {
            //获取月度信息
            //总金额
            $total_money = self::where("user_id", $user['id'])
                ->where('year', $year)
                ->where('month', $month)
                ->where("cate_type", $type)
                ->sum('total');
            $part_money = self::where("user_id", $user['id'])
                ->where('year', $year)
                ->where('month', $month)
                ->where("cate_type", $type)
                ->field("cate_id, sum(total) cate_money")
                ->order('cate_money desc')
                ->group('cate_id')
                ->select()
                ->toArray();
            $part_data = [];
            foreach ($part_money as $item) {
                if ($item['cate_money'] > 0) {
                    $cate = Db::name("user_cate")->where("id", $item['cate_id'])->find();
                    $img = $cate['img'];
                    $cate_name = $cate['cate_name'];
                    $ratio = (round($item['cate_money'] / $total_money, 4) * 100) . "%";
                    $part_detail = [];
//                    if (date("Y") == $year && date("m") == $month) {
//                        //当前月份，天数
//                        $days = date('d');
//                    } else {
                        $days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
//                    }
                    for ($i = 1; $i <= $days; $i++) {
                        $p_t = self::where("user_id", $user['id'])
                            ->where("year", $year)
                            ->where("month", $month)
                            ->where("day", $i)
                            ->where("cate_type", $type)
                            ->where("cate_id", $item['cate_id'])
                            ->sum("total");
                        array_push($part_detail, $p_t);
                    }
                    array_push($part_data, [
                        "img" => $img,
                        "cate_name" => $cate_name,
                        "cate_money" => $item['cate_money'],
                        "ratio" => $ratio,
                        "cate_detail" => $part_detail
                    ]);
                }
            }
            $month_data = [
                'total_money' => $total_money,
                'detail' => $part_data
            ];
        }

        if ($week) {
            //获取周信息
            list($start_day, $end_day) = getWeekDate($year, $week);
            $start_time = strtotime($start_day);
            $end_time = strtotime($end_day);
            //总金额
            $total_money = self::where("user_id", $user['id'])
                ->where('add_time', 'between', [$start_time, $end_time])
                ->where("cate_type", $type)
                ->sum('total');
            $part_money = self::where("user_id", $user['id'])
                ->where('add_time', 'between', [$start_time, $end_time])
                ->where("cate_type", $type)
                ->field("cate_id, sum(total) cate_money")
                ->order('cate_money desc')
                ->group('cate_id')
                ->select()
                ->toArray();
            $part_data = [];
            foreach ($part_money as $item) {
                if ($item['cate_money'] > 0) {
                    $cate = Db::name("user_cate")->where("id", $item['cate_id'])->find();
                    $img = $cate['img'];
                    $cate_name = $cate['cate_name'];
                    $ratio = (round($item['cate_money'] / $total_money, 4) * 100) . "%";
                    $part_detail = [];
                    for ($i = 0; $i <= 6; $i++) {
                        $p_t = self::where("user_id", $user['id'])
                            ->where('add_time', 'between', [$start_time + 86400 * $i, $start_time + 86400 * ($i + 1)])
                            ->where("cate_type", $type)
                            ->where("cate_id", $item['cate_id'])
                            ->sum("total");
                        array_push($part_detail, $p_t);
                    }
                    array_push($part_data, [
                        "img" => $img,
                        "cate_name" => $cate_name,
                        "cate_money"=>$item['cate_money'],
                        "ratio" => $ratio,
                        "cate_detail" => $part_detail
                    ]);
                }
            }
            $week_data = [
                'total_money' => $total_money,
                'detail' => $part_data
            ];
        }
        //获取年度信息
        $total_money = self::where("user_id", $user['id'])
            ->where('year', $year)
            ->where("cate_type", $type)
            ->sum('total');
        $part_money = self::where("user_id", $user['id'])
            ->where('year', $year)
            ->where("cate_type", $type)
            ->field("cate_id, sum(total) cate_money")
            ->order('cate_money desc')
            ->group('cate_id')
            ->select()
            ->toArray();
        $part_data = [];
        foreach ($part_money as $item) {
            if ($item['cate_money'] > 0) {
                $cate = Db::name("user_cate")->where("id", $item['cate_id'])->find();
                $img = $cate['img'];
                $cate_name = $cate['cate_name'];
                $ratio = (round($item['cate_money'] / $total_money, 4) * 100) . "%";
                $part_detail = [];
//                if (date("Y") == $year) {
//                    //当前月份
//                    $months = date('m');
//                } else {
                    $months = 12;
//                }
                for ($i = 1; $i <= $months; $i++) {
                    $p_t = self::where("user_id", $user['id'])
                        ->where("year", $year)
                        ->where("month", $i)
                        ->where("cate_type", $type)
                        ->where("cate_id", $item['cate_id'])
                        ->sum("total");
                    array_push($part_detail, $p_t);
                }
                array_push($part_data, [
                    "img" => $img,
                    "cate_name" => $cate_name,
                    "cate_money" => $item['cate_money'],
                    "ratio" => $ratio,
                    "cate_detail" => $part_detail
                ]);
            }
        }
        $year_data = [
            'total_money' => $total_money,
            'detail' => $part_data
        ];
        return [
            "month_data" => $month_data,
            "year_data" => $year_data,
            "week_data" => $week_data
        ];
    }

    /**
     * 获取月度账单信息
     */
    public static function getYearBillLog($user, $year)
    {
        $result_data = [];
        //当年支出金额
        $outlay = self::where("user_id", $user['id'])
            ->where("year", $year)
            ->where("cate_type", 1)
            ->sum("total");
        $result_data['outlay'] = $outlay;
        //当年收入金额
        $income = self::where("user_id", $user['id'])
            ->where("year", $year)
            ->where("cate_type", 2)
            ->sum("total");
        $result_data['income'] = $income;
        //每月收支状况
        if (date('Y') == $year) {
            //如果是当月，则只统计当月已经发生的日期信息
            $months = date("m");
        } else {
            $months = 12;
        }
        //账单单日记录
        $month_bill = [];
        for ($i = $months; $i >= 1; $i--) {
            $day_data = [];
            $day_data['date'] = $year . "/" . $i;
            $outlay = self::where("user_id", $user['id'])
                ->where("year", $year)
                ->where("month", $i)
                ->where("cate_type", 1)
                ->sum("total");
            $day_data['outlay'] = $outlay;
            //单日收入金额
            $income = self::where("user_id", $user['id'])
                ->where("year", $year)
                ->where("month", $i)
                ->where("cate_type", 2)
                ->sum("total");
            $day_data['income'] = $income;
            array_push($month_bill, $day_data);
        }
        $result_data['month_list'] = $month_bill;
        return $result_data;
    }


    /**
     * 获取月度账单信息
     */
    public static function getMonthBillLog($user, $year, $month)
    {
        $result_data = [];
        //预算信息
        $budget = Db::name("bill_budget")->where("user_id", $user['id'])
            ->where("year", $year)
            ->where("month", $month)
            ->withoutField('create_time, update_time')
            ->value("money");
        $result_data['budget'] = $budget ?? 0;
        //当月支出金额
        $outlay = self::where("user_id", $user['id'])
            ->where("year", $year)
            ->where("month", $month)
            ->where("cate_type", 1)
            ->sum("total");
        $result_data['outlay'] = $outlay;
        //当月收入金额
        $income = self::where("user_id", $user['id'])
            ->where("year", $year)
            ->where("month", $month)
            ->where("cate_type", 2)
            ->sum("total");
        $result_data['income'] = $income;
        //当月账单明细
        if (date('Y') == $year && date("m") == $month) {
            //如果是当月，则只统计当月已经发生的日期信息
            $days = date("d");
        } else {
            $days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        }
        //账单单日记录
        $bill_list = [];
        for ($i = $days; $i >= 1; $i--) {
            $day_data = [];
            $day_data['date'] = $year . "/" . $month . "/" . $i;
            $outlay = self::where("user_id", $user['id'])
                ->where("year", $year)
                ->where("month", $month)
                ->where("day", $i)
                ->where("cate_type", 1)
                ->sum("total");
            $day_data['outlay'] = $outlay;
            //单日收入金额
            $income = self::where("user_id", $user['id'])
                ->where("year", $year)
                ->where("month", $month)
                ->where("day", $i)
                ->where("cate_type", 2)
                ->sum("total");
            $day_data['income'] = $income;
            $day_data['bill_list'] = self::where("year", $year)
                ->where("month", $month)
                ->where("day", $i)
                ->where("user_id", $user['id'])
                ->field("id,cate_id, cate_type, cate_name,total,add_time,remarks")
                ->order("add_time desc, id desc")
                ->select()
                ->each(function ($val) use ($user) {
                    $val['img'] = Cate::getCateImg($user['id'], $val['cate_id']);
                    return $val;
                })
                ->toArray();
            if (!empty($day_data['bill_list'])) {
                array_push($bill_list, $day_data);
            }
        }
        $result_data['days_list'] = $bill_list;
        return $result_data;
    }

    /**
     * 设置预算
     * @param $user
     * @param $year
     * @param $month
     */
    public static function setBudget($user, $year, $month, $money)
    {
        $res = Db::name("bill_budget")->where("user_id", $user['id'])
            ->where("year", $year)
            ->where("month", $month)
            ->find();
        if (empty($res)) {
            //未设置过，新增
            Db::name("bill_budget")->insert([
                "user_id" => $user['id'],
                "money" => $money,
                "year" => $year,
                "month" => $month,
                "create_time" => time()
            ]);
        } else {
            //设置过，更新账户
            Db::name("bill_budget")
                ->where("id", $res['id'])
                ->update([
                    "month" => $month,
                    "update_time" => time()
                ]);
        }
        return true;
    }


    /**
     * 删除账单记录
     * @param $user_id
     * @param $bill_id
     */
    public static function delBill($user_id, $bill_id)
    {
        $info = self::where("user_id", $user_id)
            ->where("id", $bill_id)
            ->find();
        if (empty($info)) {
            throw new UserException('账单不存在');
        }
        $info->delete();
    }

    //编辑账本记录
    public static function editBill($user_id, $total, $bill_id, $add_time, $remarks)
    {
        //处理时间格式
        $time = $add_time;
        $year = date('Y', $time);
        $month = date('m', $time);
        $day = date('d', $time);
        $update_data = [
            "total" => $total,
            "year" => $year,
            "month" => $month,
            "day" => $day,
            "add_time" => $time,
            "remarks" => $remarks
        ];
        Db::name("bill")->where('id', $bill_id)->update($update_data);
    }

    //添加账本记录
    public static function addBill($user_id, $total, $cate_id, $cate_type, $add_time, $remarks)
    {
        $cate = Db::name("user_cate")
            ->where('id', $cate_id)
            ->where('cate_type', $cate_type)
            ->find();
        if (empty($cate)) {
            throw new UserException('分类不存在');
        }
        //处理时间格式
        $time = $add_time;
        $year = date('Y', $time);
        $month = date('m', $time);
        $day = date('d', $time);
        $insert_data = [
            "user_id" => $user_id,
            "total" => $total,
            "cate_id" => $cate_id,
            "cate_name" => $cate['cate_name'],
            "cate_type" => $cate_type,
            "year" => $year,
            "month" => $month,
            "day" => $day,
            "add_time" => $time,
            "create_time" => time(),
            "remarks" => $remarks
        ];
        Db::name("bill")->insert($insert_data);
    }


}